/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef EL_PROTOCOL_AUTH_PROCESSOR_H
#define EL_PROTOCOL_AUTH_PROCESSOR_H

#include <string>
#include <unordered_map>
#include <functional>
#include <chrono>
#include <nlohmann/json.hpp>
#include "command_handler_base.h"  // 添加基类头文件

namespace El {
namespace Protocol {

// 挑战码信息结构体
struct ChallengeInfo {
    std::string challenge;                              // 挑战码
    std::string username;                              // 用户名
    std::string device_id;                             // 设备ID
    std::chrono::system_clock::time_point create_time; // 创建时间
    bool used;                                         // 是否已使用
};

/**
 * @brief 身份认证处理器
 * 提供认证相关的功能，包括挑战码生成、登录、令牌刷新等
 */
class AuthProcessor : public CommandHandlerBase {  // 继承自基类
public:
    AuthProcessor() = default;
    ~AuthProcessor();

    // 禁止拷贝和赋值
    AuthProcessor(const AuthProcessor&) = delete;
    AuthProcessor& operator=(const AuthProcessor&) = delete;

    /**
     * @brief 注册认证相关的命令处理函数
     * @param method_handlers 命令处理函数映射表，键为命令名称，值为处理函数
     */
    void RegisterMethodHandlers(std::unordered_map<std::string, 
        std::function<nlohmann::json(const std::string&, const nlohmann::json&)>>& method_handlers);

    // 认证相关方法
    nlohmann::json HandleAuthGetChallenge(const std::string& id, const nlohmann::json& params);
    nlohmann::json HandleAuthLogin(const std::string& id, const nlohmann::json& params);
    nlohmann::json HandleAuthRefreshToken(const std::string& id, const nlohmann::json& params);
    nlohmann::json HandleAuthLogout(const std::string& id, const nlohmann::json& params);
    nlohmann::json HandleAuthGetSessions(const std::string& id, const nlohmann::json& params);

private:
    // 挑战码相关方法
    bool ValidateChallenge(const std::string& username, 
                          const std::string& challenge,
                          const std::string& device_id);
    bool IsExpired() const;
    std::string SHA256(const std::string& input);
    std::string GenerateRandomToken(size_t length);

private:
    // 存储最后一个挑战码信息
    ChallengeInfo last_challenge_;
    // 存储当前的access_token
    std::string current_access_token_;
    static constexpr int CHALLENGE_EXPIRE_SECONDS = 300; // 挑战码过期时间（秒）
};

} // namespace Protocol
} // namespace El

#endif // EL_PROTOCOL_AUTH_PROCESSOR_H